#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   Ssh.sh
# Version:    1.0
# Date:       2013/09/03
# Author:     yuanhui.shi
# Email:      yuanhui.shi@cs2c.com.cn
# Summary:    Format the steps of adding user and the steps of the remote connection by ssh in each testcase
# Notes:      Include Useradd and Ssh
# Copyright:  China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/09/03
#             - The first one
#	      Version 1.1,2013-09-04
#	      - Modify function Ssh by adding variable ACTION
#             Version 1.2,2013-09-04
#             -Modify function Ssh by setting password\ip\user as variable
#	      Version 1.3,2013/09/04
#             -Add public function Scp
#	      Version 1.4,2013/09/05
#             -Modify function Adduser by setting password\user as variable
# ----------------------------------------------------------------------

##! @TODO: Add user and set password when user exist
##!        Set password when user doesn't exist
##! @AUTHOR: yuanhui.shi
##! @VERSION: 1.0 
##! @OUT: The added user exist and its passwd is qwer1234.

function Adduser()
{
    USER=$1
    PASSWORD=$2
    useradd ${USER} &> /dev/null

    /usr/bin/expect <<-EOF
    spawn passwd ${USER}
    expect "Enter new password:"
    send "${PASSWORD}\r"
    expect "Re-type new password:"
    send "${PASSWORD}\r"    
    expect eof
EOF
    return 0
}

##! @TODO: Connect some system by ssh
##!        Finish some operation
##! @AUTHOR: yuanhui.shi
##! @VERSION: 1.2
##! @OUT: Login some system and make some operation on it

function Ssh ()
{
    rm -rf /root/.ssh/known_hosts
    USER=$1
    IP=$2
    PASSWORD=$3
    ACTION=$4
    /usr/bin/expect <<-EOF
    spawn ssh ${USER}@${IP} "${ACTION}"
    expect "Are you sure you want to continue connecting (yes/no)?"
    send "yes\r" 
    expect "******'s password:"
    send "${PASSWORD}\r"
    expect eof
EOF
    return 0
}

##! @TODO: Cope some files from localhost to a remote computer by scp 
##! @AUTHOR: yuanhui.shi
##! @VERSION: 1.0 
##! @OUT: Remotely cope files sucessfully

function Scp ()
{
    rm -rf /root/.ssh/known_hosts
    USER=$1
    IP=$2
    PASSWORD=$3
    FILE=$4
    FILE1=$5
    /usr/bin/expect <<-EOF
    spawn scp ${FILE} ${USER}@${IP}:${FILE1}
    expect "Are you sure you want to continue connecting (yes/no)?"
    send "yes\r" 
    expect "******'s password:"
    send "${PASSWORD}\r"
    expect eof
EOF
    return 0
}

